package controller;

import model.User;
import service.AuthService;
import view.LoginView;
import view.FrontView;
import view.AdminView;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginController {
    private LoginView view;
    private AuthService authService;

    public LoginController(LoginView view, AuthService authService) {
        this.view = view;
        this.authService = authService;

        view.addLoginListener(new LoginListener());
    }

    class LoginListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String username = view.getUsername();
            String password = view.getPassword();
            boolean isAdmin = view.isAdmin();

            try {
                User user = authService.authenticate(username, password, isAdmin);
                if (user != null) {
                    view.dispose();
                    if (isAdmin) {
                        FrontView adminView2 = new FrontView();
                        new FrontController(adminView2);
                        adminView2.setVisible(true);
                        AdminView adminView1 = new AdminView();
                        new AdminController(adminView1);
                        adminView1.setVisible(true);


                        // 管理员可以访问前台和后台
//                        new AdminView().show();
//                        new FrontView().show();
                    } else {
                        FrontView frontView = new FrontView();
                        new FrontController(frontView);
                        frontView.setVisible(true);
                    }
                } else {
                    view.showError("用户名或密码错误");
                }
            } catch (Exception ex) {
                view.showError("登录时发生错误: " + ex.getMessage());
            }
        }
    }
}
